package com.mz.ozy.activity.shop;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.jude.rollviewpager.RollPagerView;
import com.mz.ozy.R;
import com.mz.ozy.adapter.DetailBannerAdapter;
import com.mz.ozy.adapter.ShopDetailAdapter;
import com.mz.ozy.adapter.ShopDetailBannerAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.GoodsImgBean;
import com.mz.ozy.bean.ShopDetailBean;
import com.mz.ozy.bean.ShopSpecListBean;
import com.mz.ozy.bean.VirtualGoodsBean;
import com.mz.ozy.bean.VirtualOrderBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.VirtualGoodsPresenter;
import com.mz.ozy.mvp.view.VirtualGoodsContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.ScreenUtil;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.SpecPopupWindow;
import com.mz.ozy.widget.SpecVipWindow;
import com.mz.ozy.widget.dialog.VipSpecDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

public class VirtualGoodsActivity extends BaseActivity<VirtualGoodsContract.View, VirtualGoodsPresenter> implements VirtualGoodsContract.View, ViewPager.OnPageChangeListener {
    @BindView(R.id.rollPagerView)
    RollPagerView mRollPagerView;
    @BindView(R.id.tv_goods_price)
    TextView mTvPrice;
    @BindView(R.id.shopDetail)
    TextView mTvShopDetail;
    @BindView(R.id.tv_shop_desc)
    TextView mTvShopDesc;
    @BindView(R.id.tv_goods_unit)
    TextView mTvGoodsUnitBv;
    @BindView(R.id.tv_unit_price)
    TextView mTvUnitPrice;
    @BindView(R.id.tv_choose_rules)
    TextView mTvChooseRules;
    @BindView(R.id.tv_select_rules)
    TextView mTvSelectRules;
    @BindView(R.id.rv_shop_detail)
    RecyclerView mRvShopDetail;
    @BindView(R.id.tv_rollpager_hint)
    TextView mTvRollpagerHint;
    @BindView(R.id.iv_shop_info_star)
    ImageView mIvShopInfoStar;
    @BindView(R.id.tv_shop_about)
    TextView mTvShopAbout;
    @BindView(R.id.tv_detail_parameter)
    TextView mTvDetailParameter;
    @BindView(R.id.ll_detail_parameter)
    LinearLayout mLlDetailParameter;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;

    private ShopDetailBannerAdapter mBannerAdapter;
    private ShopDetailAdapter mDetailAdapter;
    private VipSpecDialog mSpecPopupWindow;
    private VirtualGoodsBean bean;
    private List<GoodsImgBean> mGoodsImgListBeans = new ArrayList<>();
    private List<ShopSpecListBean.ShopSpecBean> attribute_list;
    private int buyNumber = 1;//购买数量
    private String goodsId;
    private int mOpType = 1;
    private ShopSpecListBean mSpecListBeans;
    private int mGgId = -1;
    private int mPosition = 0;
    private boolean isFirstResume = true;
    private long curTime;
    private String startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_virtual_goods);
        ButterKnife.bind(this);
        initTitle();
        QMUIStatusBarHelper.translucent(this);
        setTitleBarMargin();
//        EventBus.getDefault().register(this);
        initData();
        mRollPagerView.setAnimationDurtion(500);
        mRollPagerView.setPlayDelay(-1);
        mRollPagerView.setHintView(null);
        mBannerAdapter = new ShopDetailBannerAdapter(this, mGoodsImgListBeans);
        mRollPagerView.setAdapter(mBannerAdapter);

        mDetailAdapter = new ShopDetailAdapter(null);
        mRvShopDetail.setLayoutManager(new LinearLayoutManager(this));
        mRvShopDetail.setAdapter(mDetailAdapter);
        mRvShopDetail.setNestedScrollingEnabled(false);
        mRollPagerView.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                final int index = position + 1;
                String hint = index + "/" + mBannerAdapter.getCount();
                mTvRollpagerHint.setText(hint);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mIvShopInfoStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.onGoodsFollow(VirtualGoodsActivity.this, goodsId);
            }
        });

        mPresenter.obtainShopDetailInfo(this, goodsId);
    }

    private void initData() {
        goodsId = getIntent().getStringExtra("goodsId");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirstResume) {
            if (mBannerAdapter != null) {
                mBannerAdapter.setPause(false);
            }
        }
        isFirstResume = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBannerAdapter != null) {
            mBannerAdapter.setPause(true);
        }
        Jzvd.resetAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void obtainShopDetailInfoSuccess(VirtualGoodsBean detailBean) {
        bean = detailBean;
        attribute_list = bean.getAttribute_list();
        final String starttime = bean.getStarttime();
        if (TextUtils.isEmpty(starttime)) {
            mTvStartTime.setVisibility(View.GONE);
        } else {
            mTvStartTime.setVisibility(View.VISIBLE);
            Date date = null;
            try {
                date = CalendarUtils.string2Date(starttime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (curTime >= date.getTime()) {
                mTvStartTime.setVisibility(View.GONE);
            } else {
                this.startTime = starttime;
                mTvStartTime.setText(CalendarUtils.date2String(date) + "开售后发货");
            }
        }
        mTvShopAbout.setText(bean.getSecurity());
        mGoodsImgListBeans.clear();
        if (!TextUtils.isEmpty(bean.getVido())) {
            mGoodsImgListBeans.add(new GoodsImgBean(bean.getVido(), 1));
        }
        if (!TextUtils.isEmpty(bean.getImg_zt())) {
            final String[] imgZtArr = bean.getImg_zt().trim().split(",");
            for (String imgPath : imgZtArr) {
                mGoodsImgListBeans.add(new GoodsImgBean(imgPath, 0));
            }
        }
        if (mGoodsImgListBeans.size() > 0) {
            mTvRollpagerHint.setText("1/" + mGoodsImgListBeans.size());
        }
        mBannerAdapter.notifyDataSetChanged();
//            mRollPagerView.pause();
        if (!TextUtils.isEmpty(bean.getImg_xq())) {
            final String[] imgXqArr = bean.getImg_xq().trim().split(",");
            final List<String> imgList = Arrays.asList(imgXqArr);
            mDetailAdapter.setNewData(imgList);
        }
        mTvShopDetail.setText(bean.getTradename());
        mTvShopDesc.setText(bean.getDescribed());

        String price = getPrice();
        mTvPrice.setText(price);
        mTvGoodsUnitBv.setText("(" + bean.getShopbv() + "BV)");
        mTvUnitPrice.setText(bean.getWeight() + "g");

        final List<VirtualGoodsBean.ParameterBean> parameterBeans = detailBean.getcList();
        if (parameterBeans == null || parameterBeans.size() == 0) {
            mTvDetailParameter.setVisibility(View.GONE);
            mLlDetailParameter.setVisibility(View.GONE);
        } else {
            for (VirtualGoodsBean.ParameterBean parameterBean : parameterBeans) {
                final View submitOrderView = View.inflate(this, R.layout.item_goods_parameter, null);
                processParameterView(submitOrderView, parameterBean);
            }
        }
    }

    private void processParameterView(View submitOrderView, VirtualGoodsBean.ParameterBean parameterBean) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLlDetailParameter.addView(submitOrderView, params);
        TextView tvCvName = submitOrderView.findViewById(R.id.tv_cv_name);
        tvCvName.setText(parameterBean.getCname());
        TextView tvCvValue = submitOrderView.findViewById(R.id.tv_cv_value);
        tvCvValue.setText(parameterBean.getCvalue());
    }

    @NotNull
    private String getPrice() {
        String price = "";
        if (!TextUtils.isEmpty(bean.getPrice()) && Double.parseDouble(bean.getPrice()) != 0.00) {
            price += "¥";
            price += Utils.decimalUtils(bean.getPrice(), 2);
        }
        if (!TextUtils.isEmpty(bean.getMarket_price()) && Double.parseDouble(bean.getMarket_price()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.decimalUtils(bean.getMarket_price(), 2);
                price += "积分";
            } else {
                price += Utils.decimalUtils(bean.getMarket_price(), 2);
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    @OnClick({R.id.buyNowTv, R.id.rl_choose_rules})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.buyNowTv:
                mOpType = 1;
                showSpecView();
                break;
            case R.id.rl_choose_rules:
                mOpType = 2;
                showSpecView();
                break;
        }
    }

    private void submitOpt() {
        if (mOpType == 0) {
            onJoinCar(mGgId);
        } else {
            onBuy(mGgId);
        }
    }

    /**
     * 显示规格判断
     */
    public void showSpecView() {
        if (mSpecListBeans == null) {
            mSpecListBeans = new ShopSpecListBean();
            String mainImg = "";
            if (mGoodsImgListBeans != null && mGoodsImgListBeans.size() > 0) {
                GoodsImgBean goodsImgBean = mGoodsImgListBeans.get(0);
                if (mGoodsImgListBeans.size() > 1 && goodsImgBean.getType() == 1) {
                    goodsImgBean = mGoodsImgListBeans.get(1);
                }
                mainImg = goodsImgBean.getImgPath();
            }
            mSpecListBeans.setOperate(false);
            mSpecListBeans.setGoodsImg(mainImg);
            mSpecListBeans.setTradeName(bean.getTradename());
            mSpecListBeans.setPrice(getPrice());
            mSpecListBeans.setList(attribute_list);
        }
        showSpecPopWindow();
    }


    public void showSpecPopWindow() {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        mSpecPopupWindow = new VipSpecDialog(this, mSpecListBeans, mOpType, mPosition, new VipSpecDialog.OnClickListener() {
            @Override
            public void onSubmit(int ggId, String name, int type, int position) {
                mPosition = position;
                mGgId = ggId;
                mTvChooseRules.setText("已选择");
                mTvSelectRules.setVisibility(View.VISIBLE);
                mTvSelectRules.setText(name);
                if (type != 2) {
                    submitOpt();
                }
            }

            @Override
            public void updateNumber(int number) {
                buyNumber = number;
            }

        });
//        mSpecPopupWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, Utils.getNavigationBarHeight(this));
//        mSpecPopupWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        mSpecPopupWindow.show(getSupportFragmentManager(), "vip");
    }

    /**
     * 加入购物车
     *
     * @param ggId
     */
    public void onJoinCar(int ggId) {
        mPresenter.onJoinCar(VirtualGoodsActivity.this, goodsId, ggId + "", buyNumber + "");
    }

    private void onBuy(int ggId) {
        mPresenter.onBuy(VirtualGoodsActivity.this, goodsId, "0", ggId + "", String.valueOf(buyNumber));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && data != null) {
//            AddressBean addressBean = (AddressBean) data.getSerializableExtra("data");
//            aid = addressBean.getId();
//            mAddressTv.setText(addressBean.getArea0idName() + addressBean.getArea1idName() + addressBean.getArea2idName() + addressBean.getShaddr());
        }
    }

    @Override
    public void updateShopSpecSuccess(Object o) {

    }

    /**
     * 立即购买
     *
     * @param
     */
    @Override
    public void onBuySuccess(VirtualOrderBean virtualOrderBean) {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        virtualOrderBean.setNum(1);
        VirtualOrderActivity.start(this, virtualOrderBean, goodsId, startTime);
    }

    public void onJoinCarSuccess(Object o) {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
        mPresenter.obtainShopDetailInfo(this, goodsId);
        ToastUtils.showToast(R.string.str_join_car_success);
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
    }

    @Override
    public void onGoodsFollowSuccess(Object o) {
        mPresenter.obtainShopDetailInfo(this, goodsId);
    }

    @Override
    public void onGoodsCancleFollowSuccess(Object o) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
